<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="companyName">
        <el-input v-model.trim="queryParams.companyName" placeholder="请输入名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <!-- <el-form-item label="禁用状态" prop="state" label-width="100px">
        <el-select v-model="queryParams.state" clearable placeholder="请选择禁用状态" @change="handleQuery"  style="width: 240px">
          <el-option v-for="item in options3" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="dataList">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司全称" v-if="columns[0].visible" prop="companyName" align="center" width="250" />
      <el-table-column label="公司简称" v-if="columns[1].visible" prop="shortName" align="center" width="100" />
      <el-table-column label="公司地址" v-if="columns[2].visible" prop="geoAddresse" align="center" width="250" />
      <el-table-column label="企业规模" v-if="columns[3].visible" prop="comSize" align="center" width="100" />
      <el-table-column label="所属行业" v-if="columns[4].visible" align="center" width="200">
        <template #default="scope" v-if="options2?.length">
        <span>{{scope.row.comIndustry }}</span>
      </template>
      </el-table-column>
      <el-table-column label="企业类型" v-if="columns[5].visible" align="center" width="100">
        <template #default="scope">
          <span>{{ scope.row.comType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司描述" v-if="columns[6].visible" prop="comDescribe" align="center" width="300" />
      <el-table-column fixed="right" label="操作" align="center" min-width="160px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model.trim="form.companyName" placeholder="请输入企业名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业简称" prop="shortName">
              <el-input v-model.trim="form.shortName" placeholder="请输入企业简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业" prop="line_code" >
              <el-select v-model="form.comIndustry" placeholder="请选择" >
                <el-option v-for="item in options2" :key="item.id" :label="item.codeName" :value="item.codeName" />
              </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业规模">
              <el-select v-model="form.comSize" placeholder="请选择">
                <el-option v-for="item in options3" :key="item.id" :label="item.codeName" :value="item.codeName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业类型">
              <el-select v-model="form.comType" placeholder="请选择">
                <el-option v-for="item in options1" :key="item.id" :label="item.codeName" :value="item.codeName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item label="企业地址" prop="geoAddresse">
            <el-input v-model="form.geoAddresse" type="textarea" :maxlength="100" placeholder="请输入企业地址" style="width: 236px" />
            <el-button type="primary" @click="openMapPicker" style="margin-left: 10px">地图选点</el-button>
         </el-form-item>
          <el-col :span="12">
            <el-form-item label="产品和业务">
              <el-input v-model="form.comDescribe" type="textarea" placeholder="请输入企业主要产品和业务" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="企业管理状态" label-width="130">
              <el-radio-group v-model="form.state">
                <el-radio :value="1">正常使用</el-radio>
                <el-radio :value="0">已停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <AMapPointPickerInDialog ref="mapPickerDialogRef" @confirm="handleConfirm" />

  </div>
</template>

<script setup>
import { useInfoStore } from '@/store/modules/info.js'
import AMapPointPickerInDialog from '@/components/Amap/AMapPointPickerInDialog.vue';
const userInfo = useInfoStore();

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");

const mapPickerDialogRef = ref(null); //地图示例

const dataList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const menuRef = ref(null);
const options1 = ref();
const options2 = ref();
const options3 = ref();
// 列显隐信息
const columns = ref([
  { key: 1, label: `公司全称`, visible: true },
  { key: 2, label: `公司简称`, visible: true },
  { key: 3, label: `公司地址`, visible: true },
  { key: 4, label: `企业规模`, visible: true },
  { key: 5, label: `所属行业`, visible: true },
  { key: 6, label: `企业类型`, visible: true },
  { key: 7, label: `公司描述`, visible: true },
]);
const data = reactive({
  form: {
    id: null,
    companyName: null,//企业名称
    shortName: null,//企业简称
    geoAddresse: null,//高德地址
    comLongitude: null,//经度
    comLatitude: null,//纬度
    comIndustry: null,//所属行业
    comType: null,//企业类型
    comSize: null,//企业规模
    comDescribe: null,//产品和业务
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    companyName: null,//名称
  },
  rules: {
    companyName: [{ required: true, message: "企业名称不能为空", trigger: "blur" }],
    companyName: [{ required: true, message: "企业名称不能为空", trigger: "blur" }],

  },
});

const { queryParams, form, rules } = toRefs(data);

// 自定义校验函数
const validateTypeOrSpec = (rule, value, callback) => {
  if (!form.value.types && !form.value.specifications) {
    callback(new Error('型号和规格至少输入一项'));
  } else {
    callback();
  }
};
// 更新校验规则
rules.value.types = { validator: validateTypeOrSpec, trigger: 'blur' };
rules.value.specifications = { validator: validateTypeOrSpec, trigger: 'blur' };

// 打开地图选点
function openMapPicker() {
  if (mapPickerDialogRef.value) {
    // 如果有经纬度，解析并传入
    let position = null;
    if (form.value.lngLat) {
      const [lng, lat] = form.value.lngLat.split(',');
      if (lng && lat) {
        position = { lng: parseFloat(lng), lat: parseFloat(lat) };
      }
    }
    mapPickerDialogRef.value.openDialog(position);
  }
}
// 地图选点信息
function handleConfirm(point) {
  if(point){
    form.value.comLongitude = point.longitude;
    form.value.comLatitude = point.latitude;
    form.value.comAddresse = point.name;
    form.value.geoAddresse = point.name;
  }
}
/** 查询角色列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetPageList(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除企业"' + row.companyName + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelCompany({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}


/** 重置新增的表单以及其他数据  */
function reset() {
  getDict()
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    id: null,
    companyName: null,//企业名称
    shortName: null,//企业简称
    geoAddresse: null,//高德地址
    comLongitude: null,//经度
    comLatitude: null,//纬度
    comIndustry: null,//所属行业
    comType: null,//企业类型
    comSize: null,//企业规模
    comDescribe: null,//产品和业务
  };
}
/** 新增物料 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}

/** 修改物料 */
function handleUpdate(row) {
  let newRow = JSON.parse(JSON.stringify(row));
  reset();
  Object.keys(form.value).forEach(key => {
    form.value[key] = newRow[key];
  });
  open.value = true;
  title.value = "修改";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.UpdateCompany({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddCompany({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
function getDict() {
  proxy.cloudTv_API.GetPubCodeList({
  codeGroup:5 //行业分类
  }).then(res => {
    options2.value = res.data || [];
  });
  proxy.cloudTv_API.GetPubCodeList({
  codeGroup:4 //企业规模
  }).then(res => {
    options3.value = res.data || [];
  });
  proxy.cloudTv_API.GetPubCodeList({
  codeGroup:3 //企业性质
  }).then(res => {
    options1.value = res.data || [];
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>

<style lang="scss" scoped>
.el-input-number {
  width: 190px;
}

.required-star {
  color: #F56C6C;
  margin-right: 4px;
}
</style>
